package org.bee.dict;

import jakarta.annotation.PostConstruct;
import org.bee.annotation.EnumsDict;
import org.bee.enums.IEnum;
import org.bee.json.JsonUtils;
import org.bee.model.DictEnums;
import org.bee.model.DictSelect;
import org.bee.redis.RedisUtils;
import org.bee.string.StringUtils;
import org.reflections.Reflections;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class EnumsDictInit {


    private final RedisUtils redisUtils;

    public EnumsDictInit(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Value("${needInitDict:false}")
    private String needInitDict;

    @PostConstruct
    public void init(){
        if(needInitDict.equals("true")){
            initDictFromEnum();
        }
    }

    /**
     * 从枚举中获取字典，同步缓存到redis中
     */
    public void initDictFromEnum(){
        Reflections reflections = new Reflections("org.bee.enums");
        Set<Class<? extends IEnum>> enumClasses = reflections.getSubTypesOf(IEnum.class);
        for (Class<? extends IEnum> enumClass : enumClasses) {
            //拿到有注解的
            EnumsDict enumsDict = enumClass.getAnnotation(EnumsDict.class);
            if (enumsDict != null) {
                DictEnums dict = new DictEnums();
                //拿到注解的值
                String desc = enumsDict.desc();
                dict.setCode(enumsDict.value());
                if(StringUtils.isNotEmpty(desc)){
                    dict.setDesc(desc);
                }
                List<DictSelect> values = new ArrayList<>();
                //获取枚举的值
                IEnum[] enumConstants = enumClass.getEnumConstants();
                for (IEnum constant : enumConstants) {
                    DictSelect dictSelect = new DictSelect();
                    // 获取每个枚举项的值和描述
                    dictSelect.setLabel(constant.getDesc());
                    dictSelect.setValue(constant.getCode());
                    values.add(dictSelect);
                }
                dict.setValues(values);
                redisUtils.set("EnumDict:"+enumsDict.value(), JsonUtils.toJson(dict));
            }
        }
    }

    public void initDictFromDb(){

    }
}
